package org.scboy.logger.detect;

import java.util.Calendar;

import org.scboy.common.cache.SystemConfig;
import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.logger.dao.LoggerDbColumnLogDao;
import org.scboy.logger.dao.LoggerDbTableLogDao;
import org.scboy.logger.dao.LoggerRequestLogDao;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;

/**
 * 检测登录状态
 */
@Configuration
@EnableScheduling
public class DbClearLogDetect {
	
	@Autowired
	SystemConfig config;

	@Autowired
	EntityFactory facotry;
	
	/**
	 * 每天0点0分0秒清理日志
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	private void detect() {

		LoggerDbTableLogDao tableDao=facotry.getDao(LoggerDbTableLogDao.class);
		LoggerDbColumnLogDao columnDao=facotry.getDao(LoggerDbColumnLogDao.class);
		LoggerRequestLogDao requestDao=facotry.getDao(LoggerRequestLogDao.class);
		
		//登录保持时长
		Integer days=Convert.toInt(config.getConfig("LOGGER_SERVER_LOG_STORAGE_PERIOD"));

		if(days > 0 ) {
			Calendar cal= Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -days);
			
			long delTime=Convert.toLong(DateUtil.format(cal.getTime(), "yyyyMMdd"));
			
			tableDao.delete(Model.create().LE("logTimeIndex", delTime));
			
			columnDao.delete(Model.create().LE("logTimeIndex", delTime));
			
			requestDao.delete(Model.create().LE("logTimeIndex", delTime));
		}
	}
}
